package com.seveneight.baijiesteward.ui.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.zxing.common.StringUtils;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.adapter.FirstAdapter;
import com.seveneight.baijiesteward.base.BaseFragment;
import com.seveneight.baijiesteward.base.MessageEvent;
import com.seveneight.baijiesteward.bean.AnyBean;
import com.seveneight.baijiesteward.bean.BannerListBean;
import com.seveneight.baijiesteward.bean.MenuBean;
import com.seveneight.baijiesteward.bean.NoticeListBean;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.http.HttpConfig;
import com.seveneight.baijiesteward.http.MyCallBack;
import com.seveneight.baijiesteward.ui.first.activity.EmptyActivity;
import com.seveneight.baijiesteward.ui.first.contract.FirstMenuContract;
import com.seveneight.baijiesteward.ui.first.fragment.CashierFragment;
import com.seveneight.baijiesteward.ui.first.fragment.MyTeamFragment;
import com.seveneight.baijiesteward.ui.first.presenter.FirstMenuPresenter;
import com.seveneight.baijiesteward.ui.main.activity.CreditCardApplicationdActivity;
import com.seveneight.baijiesteward.ui.main.activity.LoginActivity;
import com.seveneight.baijiesteward.ui.main.activity.PerfectRepaymentActivity;
import com.seveneight.baijiesteward.ui.main.activity.PlanPayListActivity;
import com.seveneight.baijiesteward.ui.main.activity.WebActivity;
import com.seveneight.baijiesteward.ui.user.activity.RecordActivity;
import com.seveneight.baijiesteward.ui.first.fragment.DrawingFragment;
import com.seveneight.baijiesteward.ui.user.fragment.IdentifyFragment;
import com.seveneight.baijiesteward.ui.user.fragment.ManagerAccountFragment;
import com.seveneight.baijiesteward.ui.user.fragment.PayBackFragment;
import com.seveneight.baijiesteward.ui.user.fragment.UpgradeFragment;
import com.seveneight.baijiesteward.ui.user.model.BranchIndexListModel;
import com.seveneight.baijiesteward.utils.GlideLoader;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.RecyclerviewInitUtil;
import com.seveneight.baijiesteward.utils.Setting;
import com.seveneight.baijiesteward.utils.StringFormat;
import com.seveneight.baijiesteward.utils.WindowUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import cc.ibooker.ztextviewlib.MarqueeTextView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by user1 on 2018/2/6.
 */

public class FirstFragment extends BaseFragment implements OnBannerListener, FirstMenuContract.MenuView {

    FirstMenuContract.MenuPresenter menuPresenter;
    private int[] iconImgs = {R.mipmap.icon_creditcar, R.mipmap.icon_myprofit,
            R.mipmap.icon_upload, R.mipmap.icon_cashier,
            R.mipmap.icon_insurance, R.mipmap.icon_qrcode,
            R.mipmap.icon_rights, R.mipmap.icon_exchange,
            R.mipmap.icon_check, R.mipmap.icon_creditapply,
            R.mipmap.icon_search, R.mipmap.icon_more};
    private ArrayList<String> banners;
    private LRecyclerView recyclerview;
    private FirstAdapter adapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CircleImageView ci_firsthead;
    private TextView tv_phone;
    private TextView tv_bill;
    private LinearLayout layout_repay2;
    private LinearLayout layout_repay1;
    private LinearLayout layout_reditcard;
    private LinearLayout notice_layout;
    private MarqueeTextView txt_notice;
    private Banner banner;
    public List<NoticeListBean> noticeListBeans;
    public List<BannerListBean> bannerListBeans;

    @Override
    protected int getContentView() {
        return R.layout.fragment_first;
    }

    public static FirstFragment newInstance() {
        Bundle args = new Bundle();
        FirstFragment fragment = new FirstFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        recyclerview = findView(R.id.recyclerview);
        View header = LayoutInflater.from(mContext).inflate(R.layout.layout_firstheader, (ViewGroup) view.findViewById(android.R.id.content), false);
        ci_firsthead = (CircleImageView) header.findViewById(R.id.ci_firsthead);
        tv_phone = header.findViewById(R.id.tv_phone);
        tv_bill = header.findViewById(R.id.tv_bill);
        layout_repay1 = header.findViewById(R.id.layout_repay1);
        layout_repay2 = header.findViewById(R.id.layout_repay2);
        layout_reditcard = header.findViewById(R.id.layout_reditcard);
        notice_layout=header.findViewById(R.id.notice_layout);
        txt_notice=header.findViewById(R.id.txt_notice);
        header.findViewById(R.id.title_firstyeader_layout).setOnClickListener(loginClickListener);
        View footer = LayoutInflater.from(mContext).inflate(R.layout.layout_firstfooter, (ViewGroup) view.findViewById(android.R.id.content), false);
        banner = footer.findViewById(R.id.banner);
        RecyclerviewInitUtil.initFirstRecycler(mContext, recyclerview);
        adapter = new FirstAdapter(mContext);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lRecyclerViewAdapter.addHeaderView(header);
        lRecyclerViewAdapter.addFooterView(footer);
        recyclerview.setAdapter(lRecyclerViewAdapter);
    }

    @Override
    protected void initData() {
//        EventBus.getDefault().register(this);
        banners = new ArrayList<>();
//        banners.add(R.mipmap.banner1);
//        banner.setImages(banners)
//                .setImageLoader(new GlideLoader())
//                .setOnBannerListener(this)
//                .start();
        menuPresenter = new FirstMenuPresenter(this);
        menuPresenter.getFirstMenu(jsonFormat.commonParam());
        getINdexList();
    }
    public void getINdexList(){
        new BranchIndexListModel().getBankList(getActivity(), jsonFormat.commonParam(), new MyCallBack<AnyBean>() {
            @Override
            public void onSuccess(AnyBean anyBeans) {
                noticeListBeans= JSON.parseArray(anyBeans.getNoticeList(),NoticeListBean.class);
                bannerListBeans= JSON.parseArray(anyBeans.getBannerList(),BannerListBean.class);
                if (noticeListBeans.size()>0){
                    if (!com.seveneight.baijiesteward.utils.StringUtils.isEmpty(noticeListBeans.get(0).getContent())){
                        notice_layout.setVisibility(View.VISIBLE);
                        txt_notice.setText(noticeListBeans.get(0).getContent());
                    }
                }
                for (int i=0;i<bannerListBeans.size();i++){
                    banners.add(HttpConfig.SOURCE_URL+bannerListBeans.get(i).getImgUrl());
                }
                if (banners.size()>0){
                    loadImage();
                }
            }

            @Override
            public void onFailed() {

            }
        });
    }
    public void loadImage(){
        banner.updateBannerStyle(BannerConfig.NOT_INDICATOR);
        banner.setImages(banners)
                .setImageLoader(new GlideLoader())
                .setOnBannerListener(this)
                .setDelayTime(3000)
                .isAutoPlay(true)
                .start();
    }

    @Override
    protected void setListener() {
        tv_bill.setOnClickListener(authClickListener);
        layout_repay1.setOnClickListener(authClickListener);
        layout_repay2.setOnClickListener(authClickListener);
        layout_reditcard.setOnClickListener(authClickListener);
        txt_notice.setOnClickListener(authClickListener);
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                MenuBean menuBean = adapter.getDataList().get(position);
                recyclerClick(menuBean);
            }
        });
    }

    private void recyclerClick(MenuBean menuBean) {
        if (!setting.isLogin()) {
            WindowUtil.getInstance().startUpActivity(getActivity(), LoginActivity.class);
            return;
        }
        if (menuBean.getModuleName().equals("信用卡申请")) {
            startActivity(new Intent(getContext(),CreditCardApplicationdActivity.class));
//            Bundle bundle = new Bundle();
//            bundle.putString("url", AppConfig.MAKECARD);
//            WindowUtil.getInstance().startActivity(getActivity(), WebActivity.class, bundle);
            return;
        }
        if (userBean.getAuthStatus().equals("-1")){
            showDialog("实名审核中，请稍后再试");
            return;
        }
        if (!userBean.getAuthStatus().equals("1")) {
            showIdentifyDialog();
            return;
        }

        if (menuBean.getModuleName().equals("收银台")) {
            ((MainFragment) getParentFragment()).startBrotherFragment(CashierFragment.newInstance());
        } else if (menuBean.getModuleName().equals("升级")) {
            ((MainFragment) getParentFragment()).startBrotherFragment(UpgradeFragment.newInstance());
        } else if (menuBean.getModuleName().equals("会员权益")) {
            ((MainFragment) getParentFragment()).startBrotherFragment(UpgradeFragment.newInstance());
        } else if (menuBean.getModuleName().contains("还款金")) {
            if (userBean.getIsSetTradePassword()) {
                ((MainFragment) getParentFragment()).startBrotherFragment(PayBackFragment.newInstance());
            }else {
                showDialog();
            }
        } else if (menuBean.getModuleName().equals("我的收益")) {
            if (userBean.getIsSetTradePassword()){
                ((MainFragment) getParentFragment()).startBrotherFragment(DrawingFragment.newInstance());
            }else {
                showDialog();
            }
        } else if (menuBean.getModuleName().equals("我的团队")) {
            ((MainFragment) getParentFragment()).startBrotherFragment(MyTeamFragment.newInstance());
        } else {
            Bundle bundle = new Bundle();
            if (TextUtils.isEmpty(menuBean.getLink())) {
                bundle.putString("title", menuBean.getModuleName());
                WindowUtil.getInstance().startActivity(mContext, EmptyActivity.class, bundle);
            } else {
                bundle.putString("url", menuBean.getLink());
                WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle);
            }

        }
    }


    @Override
    public void OnBannerClick(int position) {
        if (!com.seveneight.baijiesteward.utils.StringUtils.isEmpty(bannerListBeans.get(position).getSkipLink().trim())){
            Bundle bundle5 = new Bundle();
            bundle5.putString("url", bannerListBeans.get(position).getSkipLink());
            WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle5);
        }
    }

    @Subscribe
    public void onEvent(MessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case 1:
                initUI();
                break;
        }
    }

    private void initUI() {
        if (setting.isLogin()) {
            UserBean userBean = Setting.getInstance(mContext).getUserInfo();
            tv_phone.setText(StringFormat.getPhoneNumber(userBean.getMobilePhone()));
            LogUtil.d("刷新首页界面" + userBean.toString());
            if (!TextUtils.isEmpty(setting.getHeadImgUrl())) {
                LogUtil.d("首页头像" + setting.getHeadImgUrl());
                GlideLoader.displayImg(mContext, setting.getHeadImgUrl(), ci_firsthead);
            } else {
                GlideLoader.displayImg(mContext, R.mipmap.user_head, ci_firsthead);
            }
        } else {
            tv_phone.setText("未登录");
            GlideLoader.displayImg(mContext, R.mipmap.user_head, ci_firsthead);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void rebackMenuList(List<MenuBean> data) {
        adapter.addAll(data);
        lRecyclerViewAdapter.notifyDataSetChanged();
    }


    View.OnClickListener loginClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!setting.isLogin()) {
                WindowUtil.getInstance().startUpActivity(getActivity(), LoginActivity.class);
                return;
            }
            switch (view.getId()) {

            }
        }
    };

    View.OnClickListener authClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!setting.isLogin()) {
                WindowUtil.getInstance().startUpActivity(getActivity(), LoginActivity.class);
                return;
            }
            if (userBean.getAuthStatus().equals("-1")) {
                showDialog("实名审核中，请稍后再试");
                return;
            }

            if (!userBean.getAuthStatus().equals("1")) {
                showIdentifyDialog();
                return;
            }
            switch (view.getId()) {
                case R.id.layout_repay1:
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("url", AppConfig.FAST_REPAY + setting.getUserID() + "&Signature=123");
                    WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle2);
                    break;
                case R.id.layout_repay2:
                    startActivity(new Intent(getContext(),PlanPayListActivity.class));
//                    startActivity(new Intent(getContext(),PerfectRepaymentActivity.class));
//                    Bundle bundle3 = new Bundle();
//                    bundle3.putString("url", AppConfig.PERFECT_REPAY + setting.getUserID() + "&Signature=123");
//                    WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle3);
                    break;
                case R.id.tv_bill:
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("type", "");
                    WindowUtil.getInstance().startActivity(mContext, RecordActivity.class, bundle1);
                    break;
                case R.id.layout_reditcard:
                    if (userBean.getIsSetTradePassword()){
                        ((MainFragment) getParentFragment()).startBrotherFragment(CashierFragment.newInstance());
                    }else {
                        showDialog();
                    }
                    break;
                case R.id.txt_notice:
                    Bundle bundle5 = new Bundle();
                    bundle5.putString("url", noticeListBeans.get(0).getLink());
                    WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle5);
                    break;
            }
        }
    };
    public void showDialog(){
        new MaterialDialog.Builder(getContext())
                .title("设置提醒")
                .titleColorRes(R.color.graytext)
                .content("请先设置交易密码")
                .contentColorRes(R.color.graytext)
                .backgroundColorRes(R.color.white)
                .negativeColorRes(R.color.mainblue)
                .negativeText(R.string.negative)
                .positiveColorRes(R.color.mainblue)
                .positiveText(R.string.positive)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        ((MainFragment) getParentFragment()).startBrotherFragment(ManagerAccountFragment.newInstance());
                    }
                })
                .build().show();
    }

    public void showIdentifyDialog() {
        NormalDialog dialog = new NormalDialog(mContext);
        dialog.content("请进行实名认证")//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(18)//
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        ((MainFragment) getParentFragment()).startBrotherFragment(IdentifyFragment.newInstance());
                        dialog.dismiss();
                    }
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initUI();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initUI();
    }
}
